#!/bin/bash

. $OPENARS_HOME/common/debug.h
. $OPENARS_HOME/common/functions.h

user=$USER_ARS
[ -z "$user" ] && user=$LOGNAME

>$OUTFILE

SUDO=/usr/local/bin/sudo

# $OUTFILE --> DB
function update_db() {
$ORACLE_HOME/bin/sqlplus >&2 -s /NOLOG << END
    WHENEVER SQLERROR EXIT SQL.SQLCODE
    set feedback off
    connect $CONNECT_ARS
    @"$OUTFILE"
    commit;
    exit;
END
    return $?
}

srvlist=$( $ORACLE_HOME/bin/sqlplus -s /NOLOG << END
SET PAGESIZE 0
SET HEADING OFF
SET FEEDBACK OFF
WHENEVER SQLERROR EXIT SQL.SQLCODE
connect $CONNECT_ARS
select distinct host from pass_expiration_users ;
exit;
END
)
    exit_code=$?
[ "$exit_code" -ne 0 ] && { echo "$srvlist" | sed s/\*// >&2; exit $exit_code; }

INF "pass_expiration_users have `echo $srvlist | wc -w | awk '{print $1}'` hosts"


for server in $srvlist
do
	( result=""
	  SSH $user@$server "$SUDO cat /etc/shadow" result
	  echo "$result" | grep -v ^$ > $TEMPDIR/${server}.shadow
	) &
done

wait

cd $TEMPDIR
for ServerFile in *.shadow ; do

	server="`echo $ServerFile|awk -F\. '{print $1}'`"
	ServerSql=`echo $server|sed "s/.*/\'&\'/g"`
	userlist=""
	userlist=$( $ORACLE_HOME/bin/sqlplus -s /NOLOG << END
SET PAGESIZE 0
SET HEADING OFF
SET FEEDBACK OFF
WHENEVER SQLERROR EXIT SQL.SQLCODE
connect $CONNECT_ARS
select login from pass_expiration_users where host=${ServerSql};
exit;
END
)
    exit_code=$?
[ "$exit_code" -ne 0 ] && { echo "$srvlist" | sed s/\*// >&2; exit $exit_code; }

	if [ -z "$userlist" ]; then
	    WARN "not find users in table pass_expiration_users for $server"
	    continue
	fi

	for user in $userlist
	do
	    line=""
	    Login="$user"
	    ChangeDateStr=""
	    PassLife=""
	    Error="OK"
	    if [ ! -s $ServerFile ]; then
		Error="not get /etc/shadow from server $server"
	    else
	      line=`grep ^$user $ServerFile`
	      if [ -z "$line" ]; then
		Error="not find user $user in server $server"
	        ERR "$Error"
	      else	
		ChangeDate="`echo $line|awk -F\: '{print $3}'`"
		if [ -z "$ChangeDate" ]; then
		    Error="fild change_date is empty in $server:/etc/shadow for user $Login"
    	    	    WARN "$Error"
		elif [ "$ChangeDate" == "0" ]; then
		    Error="fild change_date = 0 in $server:/etc/shadow for user $Login"
	    	    WARN "$Error"
		else 
		    ChangeDateStr="`echo "0t$(expr ${ChangeDate} \* 86400)=Y"|/usr/bin/adb|awk '{printf "%s.%s.%s\n",$3,$2,$1}'`"
		fi 
		PassLife="`echo $line|awk -F\: '{if ($5){print$5}else{print 99999}}'`"
	      fi
	    fi  
	    echo "update pass_expiration_users set change_date='$ChangeDateStr', pass_life='$PassLife', Error='$Error' where login='$Login' and host='$server';" >> $OUTFILE
	done
done

update_db
if [ "$?" -ne 0 ]; then
    ERR "error function update_db()"
    exit 1
fi

exit 0;
